package com.edu.zju.scs.panacea.service.resource;

import com.edu.zju.scs.panacea.entity.BaseResult;
import com.edu.zju.scs.panacea.entity.manage.Admin;
import com.edu.zju.scs.panacea.entity.resource.Site;
import com.edu.zju.scs.panacea.mapper.resource.SiteMapper;
import com.edu.zju.scs.panacea.utils.MathUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;

@Service
public class SiteService {

    @Autowired
    private SiteMapper siteMapper;

    public BaseResult getSite(Long id) {
        BaseResult baseResult = new BaseResult();
        Site site = siteMapper.selectSite(id);
        if (site == null) {
            baseResult.error("无此id对应的站点");
        } else {
            baseResult.success(site);
        }
        return baseResult;
    }

    public BaseResult getAllSite() {
        BaseResult baseResult = new BaseResult();
        baseResult.success(siteMapper.selectAllSite());
        return baseResult;
    }

    public BaseResult deleteSite(Long id) {
        BaseResult baseResult = new BaseResult();
        long deleteNums = siteMapper.deleteSite(id);
        if (deleteNums == 0) {
            baseResult.error("删除失败！");
        } else {
            baseResult.success(deleteNums);
        }
        return baseResult;
    }

    public BaseResult addSite(Site site) {
        BaseResult baseResult = new BaseResult();
        setInitialPassword(site);
        Long siteId = siteMapper.insertSite(site);
        if (siteId == null) {
            baseResult.error("新增站点失败！");
        } else {
            baseResult.success(siteId);
        }
        return baseResult;
    }

    public BaseResult editSite(Site site) {
        BaseResult baseResult = new BaseResult();
        Long siteId = siteMapper.updateSite(site);
        if (siteId == null) {
            baseResult.error("更新站点失败！");
        } else {
            baseResult.success(siteId);
        }
        return baseResult;
    }


    public BaseResult isValidSite(String name, String password, HttpSession session) {
        Site site = siteMapper.selectValidSite(name, password);
        BaseResult baseResult = new BaseResult();
        if (site == null) {
            baseResult.error("用户名或密码错误");
        }
        else {
            baseResult.success(site);
            session.setAttribute("site", site);
        }
        return baseResult;
    }


    private void setInitialPassword(Site site) {
        site.setPassword(MathUtil.RandomSixBit().toString());
    }
}
